package cipher

import (
	"crypto"
	"golang.org/x/crypto/pbkdf2"
	"math/rand"
	"strconv"
)

const (
	DEFAULT_SALT       = "pdc"
	DEFAULT_ITER       = 1024
	DEFAULT_KEY_LENGTH = 32
	DEFAULT_HASH       = crypto.SHA1
)

type Pbkdf2 struct {
	Password  []byte
	Salt      []byte
	Iter      int
	KeyLength int
	Hash      crypto.Hash
}

func Pbkdf2Length(length int) []byte {
	pbk := Pbkdf2{
		Password:  []byte(strconv.Itoa(rand.Int())),
		KeyLength: length,
	}
	return pbk.Key()
}

func Pbkdf2Key(password string) []byte {
	pbk := Pbkdf2{
		Password: []byte(password),
	}
	return pbk.Key()
}

func (p *Pbkdf2) Key() []byte {
	if p.Password == nil || len(p.Password) == 0 {
		panic("password can not be empty")
	}
	if p.Salt == nil || len(p.Salt) == 0 {
		p.Salt = []byte(DEFAULT_SALT)
	}
	if p.Iter < 0 {
		p.Iter = DEFAULT_ITER
	}
	if p.KeyLength <= 0 {
		p.KeyLength = DEFAULT_KEY_LENGTH
	}
	if p.Hash <= 0 {
		p.Hash = DEFAULT_HASH
	}
	return pbkdf2.Key(p.Password, p.Salt, p.Iter, p.KeyLength, FHashType(p.Hash))
}
